<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="菜单分组名称" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择上级">
          <el-option
            v-for="item in parentList"
            :key="item.id"
            :label="item.groupName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单对象" prop="target">
        <el-select v-model="queryParams.target" placeholder="请选择菜单对象">
          <el-option
            v-for="item in roleTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleshare"
        >分配权限</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="100" align="center"/>
      <el-table-column label="菜单名称" prop="name" width="150"/>
      <el-table-column label="菜单对象" prop="target" width="100">
        <template slot-scope="scope">
            <span>{{ scope.row.target === '0'?'公用': scope.row.target === '1'? '老师':'家长'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单路由" prop="router" />
      <el-table-column label="菜单logo" align="center" prop="logo" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改评教指标对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择上级">
            <el-option
              v-for="item in parentList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单路由" prop="router">
          <el-input v-model="form.router" placeholder="请输入菜单路由" />
        </el-form-item>

        <el-form-item label="菜单logo" prop="logo">
          <el-input v-model="form.logo" placeholder="请输入菜单logo" />
        </el-form-item>
        <el-form-item label="菜单对象" prop="target">
            <el-select v-model="form.target" placeholder="请选择菜单对象">
                <el-option
                    v-for="item in roleTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改分配 -->
    <el-dialog  :close-on-click-modal="false" :title="fptitle" :visible.sync="fpopen" width="50%" append-to-body>
      <el-form :model="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="班级" prop="classId">
            <el-select v-model="queryForm.classId" clearable filterable placeholder="请选择班级" @change="getclassmenu">
                <el-option
                    v-for="item in classList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                    size="small">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="菜单对象" prop="bindObject">
            <el-select v-model="queryForm.bindObject" placeholder="请选择菜单对象" @change="getclassmenu">
            <el-option
                v-for="item in roleTypeList2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
            </el-select>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="classmenuList"
        row-key="id"
        ref="multipleTable"
        @selection-change="handleSelectMenuChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column label="菜单名称" prop="name"/>
        <el-table-column label="菜单对象" prop="target" align="center">
            <template slot-scope="scope">
                <span>{{ scope.row.target === '0'?'公用': scope.row.target === '1'? '老师':'家长'}}</span>
            </template>
      </el-table-column>
        <el-table-column label="菜单路由" prop="router" width="400"/>
      </el-table>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormfp">确 定</el-button>
        <el-button @click="cancelfp">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  addmenu,
  delmenu,
  listmenu,
  listmenugroup,
  updatemenu,
  getMenuList,
  listTargetMenu,
  updateClassmenu,
  updateClaTarMenu,
  selectTarMenuList
} from "@/api/base/wechatmenu";
import {selectClazz} from "@/api/base/clazz";

export default {
  name: "menupage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 评教指标表格数据
      menuList: [],
      // 评教指标树选项
      parentList: [],
    //   菜单对象
      roleTypeList:[
        {id:'0',name:'公用'},
        {id:'1',name:'老师'},
        {id:'2',name:'家长'}
      ],
      roleTypeList2:[
        {id:'1',name:'老师'},
        {id:'2',name:'家长'}
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "上级不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        router: [
          { required: true, message: "菜单路由不能为空", trigger: "blur" }
        ],
        logo: [
          { required: true, message: "菜单logo不能为空", trigger: "blur" }
        ],
        target: [
          { required: true, message: "菜单对象不能为空", trigger: "blur" }
        ],
      },
      total:0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      fptitle:'分配权限',
      // 是否显示弹出层
      fpopen: false,
      // 分配权限参数
      queryForm:{},
      classList: [],
      classmenuList:[],
      changeMenulist:[],
      // 选中的菜单id
      selectMenu:[],
    };
  },
  created() {
    this.getList();
    //父级下拉
    this.getTreeselect()

  },
  methods: {
    /** 查询评教指标列表 */
    // getList() {
    //     new Promise((resolve, reject) => {
    //       this.loading = true;
    //       listmenugroup(this.queryParams).then(res=>{
    //         if(res.code==200){
    //           this.menuList= res.rows.map((item,index)=>{
    //             item.groupId=0
    //             item.children=[]
    //             item.name=item.groupName
    //             return item
    //           });
    //           console.log(this.menuList)
    //           this.total = res.total;
    //           this.loading = false;
    //           resolve()
    //         }
    //       })
    //
    //     }).then(()=>{
    //       listmenu(this.queryParams).then(res=>{
    //
    //         if(res.code==200){
    //           let array=[];
    //           array=this.menuList.concat(res.rows.map(item=>{
    //             item.children=[]
    //             return item
    //           }))
    //           console.log(array)
    //           this.menuList= this.handleTree(array, "id", "groupId");
    //           console.log(this.menuList)
    //         }
    //       })
    //     })
    // },
    async getList() {
      try{
        this.loading = true;
        const data=await listmenu(this.queryParams)
        this.menuList= data.rows;
        this.total = data.total;
        this.loading = false;
      }catch (e) {
        console.log(e)
      }
    },
    /**班级*/
    async getclassList() {
      try {
        const {rows} = await selectClazz();
        this.classList = rows.map(item => {
          return {
            id: item.id,
            label: item.title,
          }
        })
        //默认选择第一个班级
        this.queryForm.classId = this.classList[0].id
      } catch (e) {
        console.log(e)
      }
    },
    /** 查询父下拉结构 */
    async getTreeselect() {
      try{
        const data=await listmenugroup(this.queryParams)
        this.parentList= data.rows;
      }catch (e) {
        console.log(e)
      }
    },
    /**分配权限**/
    async handleshare(){
      try {
        this.fpopen=true
        // 设置菜单对象默认值
        this.queryForm.bindObject = this.roleTypeList2[0].id
        // 班级下拉
        await this.getclassList()
        //根据班级及对象查menu
        this.getclassmenu()
      }catch (e) {
        console.log(e)
      }
    },
    async getclassmenu(){
      try {
        const {classId,bindObject} = this.queryForm
        const params =  ['0', bindObject]
        // 查菜单
        const {rows}= await listTargetMenu(params)
        this.classmenuList = rows
        // 获取选中的菜单--接口
        const data = await selectTarMenuList(this.queryForm)
        this.selectMenu = data.rows
        // 判断是否选中
        this.$nextTick(()=>{
          this.tocheck(this.classmenuList, this.selectMenu)
        })

      }catch (e) {
        console.log(e)
      }
    },
    /**判断哪些菜单已分配权限**/
    tocheck(source,target){
      if (source && target) {
            target.forEach(tItem=>{
                source.forEach(sItem =>{
                    if(tItem.miniMenuId === sItem.id){
                        this.$refs.multipleTable.toggleRowSelection(sItem, true);
                    }
                })
            })
      }
    },
    /**分配确定**/
    async submitFormfp(){
      try {
        const {classId,bindObject} = this.queryForm
        let obj={}
        const params = []
        this.changeMenulist.forEach(item=> {
            obj={
                classId,
                bindObject,
                miniMenuId:item.id
            }
           params.push(obj)
        })
        console.log('this.changeMenulist',this.changeMenulist);
        const data = await updateClaTarMenu(params)
        this.msgSuccess("分配成功");
        this.fpopen = false;
      }catch (e) {
        console.log(e)
      }
    },
    /* 分配权限多选框数据 */
    handleSelectMenuChange(selection){
        this.changeMenulist = selection
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //分配取消按钮
    cancelfp(){
      this.fpopen = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        title: null,
        listSort: null,
        status: "1",
        score: null,
        min: null,
        max: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加菜单名称";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
      this.title = "修改菜单名称";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatemenu(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addmenu(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;

      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delmenu(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    }
  }
};
</script>
